﻿Imports TBCC.UtilityMobile
Public Class TcpConnectForm

    Private _pi As ProjectItem = MainForm.pi
    Private _isConnected As Boolean = False
    Private _isBusy As Boolean = False
    Private _isCancel As Boolean = False
    Private _isAuthFail As Boolean = False
    Private _checkRef As Boolean = True
    Private _retryTime As Integer = 30
    Private _isRetry As Boolean = False
    Private _connTime As Integer = 10
    Private _connectState As String

    Private Sub TcpConnectForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.CenterToParent()
        Me.DialogResult = Windows.Forms.DialogResult.None
        _connectState = "正在连接({0})" & _pi.Phone & ":" & _pi.ComNumber & "..."
        Me.labState.Text = String.Format(_connectState, _connTime)
        Me.TimerConnect.Start()

        Dim beginCall As New AsyncCallback(AddressOf BeginConnect)
        Dim endCall As New AsyncCallback(AddressOf EndConnect)
        beginCall.BeginInvoke(Nothing, endCall, Nothing)
    End Sub

    Private Sub btnConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConnect.Click

        If sender.Text = "关闭" Then
            Me.DialogResult = Windows.Forms.DialogResult.OK
            'Me.Close()
        ElseIf sender.Text = "取消" Then
            _isCancel = True
            COMHelper.Instance.Close(True)
            SetCancel("连接已取消")
        Else
            _isCancel = False
            'Me.btnConnect.Enabled = False
            Me.btnConnect.Text = "取消"
            Me.labState.Text = String.Format(_connectState, _connTime)
            Me.TimerRetry.Stop()
            Me.TimerConnect.Stop()
            Me.TimerConnect.Start()

            Dim beginCall As New AsyncCallback(AddressOf BeginConnect)
            Dim endCall As New AsyncCallback(AddressOf EndConnect)
            beginCall.BeginInvoke(Nothing, endCall, Nothing)
        End If

    End Sub

    Private Sub BeginConnect(ByVal ar As IAsyncResult)
        _isBusy = True

        Dim projectID As String = MainForm.pi.ProjectID
        Dim idleTime, waitTime, rep As String
        idleTime = KeyValuePairClass.GetValue(projectID, "ClientSocket_Heartbeat_IdleTime")
        waitTime = KeyValuePairClass.GetValue(projectID, "ClientSocket_Heartbeat_WaitTime")
        rep = KeyValuePairClass.GetValue(projectID, "ClientSocket_Heartbeat_Rep")
        If idleTime.Length = 0 Then
            COMHelper.Instance.SocketParameters.Heartbeat_IdleTime = 60000
        Else
            COMHelper.Instance.SocketParameters.Heartbeat_IdleTime = CInt(idleTime) * 1000
        End If
        If waitTime.Length = 0 Then
            COMHelper.Instance.SocketParameters.Heartbeat_WaitTime = 5000
        Else
            COMHelper.Instance.SocketParameters.Heartbeat_WaitTime = CInt(waitTime) * 1000
        End If
        If rep.Length = 0 Then
            COMHelper.Instance.SocketParameters.Heartbeat_Rep = 3
        Else
            COMHelper.Instance.SocketParameters.Heartbeat_Rep = CInt(rep)
        End If

        _isConnected = COMHelper.Instance.InitSocket(_pi.Phone, _pi.ComNumber)

        If _isConnected = True Then
            _isConnected = False

            Dim strResult As String
            strResult = COMHelper.Instance.WriteCommand(UtilityClass.GetAuthCodeByte(_pi.AuthCode), 10, 10000)
            If strResult.IndexOf("AT^AUTH=OK") >= 0 Then
                _isConnected = True
                _isAuthFail = False
            Else
                _isAuthFail = True
            End If

        End If

    End Sub

    Private Delegate Sub VoidMethodHandler(ByVal obj As Object)
    Private Sub EndConnect(ByVal ar As IAsyncResult)
        _isBusy = False
        Try
            If _isCancel Then
                If Me.InvokeRequired Then
                    Me.Invoke(New VoidMethodHandler(AddressOf SetCancel), "连接已取消。")
                Else
                    SetCancel("连接已取消。")
                End If
                Exit Sub
            End If

            If _isAuthFail Then
                If Me.InvokeRequired Then
                    Me.Invoke(New VoidMethodHandler(AddressOf SetCancel), "鉴权失败。")
                Else
                    SetCancel("鉴权失败。")
                End If
                Exit Sub
            End If

            If _isConnected Then
                If Me.InvokeRequired Then
                    Me.Invoke(New VoidMethodHandler(AddressOf SetConnect), "连接成功。")
                Else
                    SetConnect("连接成功。")
                End If
            Else
                If Me.InvokeRequired Then
                    Me.Invoke(New VoidMethodHandler(AddressOf SetDisConnect), "连接失败。")
                Else
                    SetDisConnect("连接失败。")
                End If
            End If
        Catch ex As Exception
            Debug.Write("TcpConnectForm.EndConnect()")
        End Try
    End Sub
    Private Sub SetConnect(ByVal str As Object)
        Me.labState.Text = str
        Me.btnConnect.Enabled = True
        Me.TimerConnect.Stop()
        'Me.Close()
        If _isRetry Then
            Me.DialogResult = Windows.Forms.DialogResult.OK
        Else
            _connTime = 3
            Me.TimerConnect.Start()
            Me.btnConnect.Text = "关闭"
        End If
    End Sub
    Private Sub SetDisConnect(ByVal str As Object)
        Me.labState.Text = str
        Me.btnConnect.Enabled = True
        Me.btnConnect.Text = "重试"
        Me.TimerRetry.Stop()
        Me.TimerConnect.Stop()
        Me._retryTime = 30
        Me._connTime = 10
        If _isRetry Then Me.TimerRetry.Start()
    End Sub
    Private Sub SetCancel(ByVal str As Object)
        Me.labState.Text = str
        'Me.btnConnect.Enabled = True
        Me.btnConnect.Text = "连接"
        Me._connTime = 10
        Me.TimerConnect.Stop()
    End Sub
    Private Sub SetState(ByVal str As Object)
        If Me.InvokeRequired Then
            Me.Invoke(New VoidMethodHandler(AddressOf SetStateMethod), str)
        Else
            Me.labState.Text = str
        End If
    End Sub
    Private Sub SetStateMethod(ByVal obj As Object)
        Me.labState.Text = obj
    End Sub

    Private Sub TcpConnectForm_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
        'e.Cancel = False
        'If _isBusy Then
        '    Me.labState.Text = "正在取消连接..."
        '    _isCancel = True
        '    e.Cancel = True
        'End If

        If Not Me._isConnected Then
            COMHelper.Instance.Close(True)
        Else
            Me.DialogResult = Windows.Forms.DialogResult.OK
        End If
        Me.TimerRetry.Stop()
        Me.TimerRetry.Dispose()
        Me.TimerConnect.Stop()
        Me.TimerConnect.Dispose()
    End Sub

    Private Sub Retry()
        _retryTime -= 1
        SetState(String.Format("{0}秒后重试...", _retryTime))
        If _retryTime <= 0 Then
            Me.TimerRetry.Stop()
            If Me.InvokeRequired Then
                Me.Invoke(New MethodInvoker(AddressOf Me.btnConnect.PerformClick))
            Else
                Me.btnConnect.PerformClick()
            End If
        End If
    End Sub

    Private Sub TimerRetry_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TimerRetry.Tick
        Retry()
    End Sub

    Private Sub TimerConnect_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TimerConnect.Tick
        _connTime -= 1

        If _isConnected Then
            Me.labState.Text = String.Format("{0}秒后关闭", _connTime)

            If _connTime <= 0 Then
                Me.TimerConnect.Stop()
                Me.DialogResult = Windows.Forms.DialogResult.OK
            End If
        Else
            Me.labState.Text = String.Format(_connectState, _connTime)

            If _connTime <= 0 Then
                Me.TimerConnect.Stop()
                COMHelper.Instance.Close(True)
            End If
        End If
    End Sub

    Public Sub New()

        ' 此调用是 Windows 窗体设计器所必需的。
        InitializeComponent()

        ' 在 InitializeComponent() 调用之后添加任何初始化。

    End Sub
    Public Sub New(ByVal isRetry As Boolean)

        ' 此调用是 Windows 窗体设计器所必需的。
        InitializeComponent()

        ' 在 InitializeComponent() 调用之后添加任何初始化。
        Me._isRetry = isRetry
    End Sub
End Class